package middleware

import (
	"hotgo/internal/controller/api/wxapp"
	"strings"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/golang-jwt/jwt/v5"
)

func JWTAuth(r *ghttp.Request) {
	// --  @# 不处理api.json 对应的swagger路由
	if strings.Contains(r.URL.Path, "api.json") {
		r.Middleware.Next()
		return
	}
	handler := r.GetServeHandler()
	isAuth := handler.GetMetaTag("auth")
	if "true" == isAuth {
		// Get token from Authorization header
		tokenString := r.Header.Get("Authorization")
		if tokenString == "" {
			r.Response.WriteJson(ghttp.DefaultHandlerResponse{
				Code:    gcode.CodeNotAuthorized.Code(),
				Message: "No token provided",
			})
			return
		}

		// Remove 'Bearer ' prefix if present
		if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
			tokenString = tokenString[7:]
		}

		// Parse and validate the token
		claims := &wxapp.JWTClaims{}
		token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
			return g.Cfg().MustGet(r.GetCtx(), "jwt.secret", "4a26fb0c0810b632d82f2ef195bd9f090dd1413cea14b2f0b8d9e56491ad50a1").Bytes(), nil
		})

		if err != nil || !token.Valid {
			r.Response.WriteJson(ghttp.DefaultHandlerResponse{
				Code:    gcode.CodeNotAuthorized.Code(),
				Message: "Invalid token",
			})
			return
		}

		// Store username in context for later use
		r.SetCtxVar("openid", claims.Openid)
	}
	r.Middleware.Next()
}
